import {useState} from 'react';
import {Button, Col, Descriptions, message, Row, Table, Tabs, Tag} from 'antd';
import HttpRequest from "@/utils/HttpRequest";
import {defaultDomain} from "@/config/domain";
import {ModalForm} from '@ant-design/pro-form'
import ReactJson from 'react-json-view'
import onCopy, {FormatDateTime} from "@/utils/DateTime";

const {TabPane} = Tabs

export function MessageDetail(prop: {
  record: {
    key: any
    tag: any
    storeSize: any
    bornTimestamp: any
    storeHost: any
    mv: boolean
    msgId: string
    topic: string
  }
}) {
  const [msgDetail, setMsgDetail] = useState({})
  const [msgDataList, setMsgDataList] = useState([])
  const [trackDataList, setTrackDataList] = useState([])

  async function getMessage(record: { key?: any; tag?: any; storeSize?: any; bornTimestamp?: any; storeHost?: any; mv?: boolean; msgId: any; topic: any; messageTrackList?: any; messageBody?: any; isJson?: any; }) {
    // @ts-ignore
    let url =
      '/message/viewMessage.query?msgId=' +
      record.msgId +
      '&topic=' +
      record.topic
    const res = await HttpRequest({
      baseURL: defaultDomain,
      url: url,
      method: 'GET',
      params: {},
    })

    console.log('res=', res)
    // @ts-ignore
    const status = res.status
    if (status === 0) {
      const resData = res.data
      if (resData) {
        const messageView = resData.messageView
        record.messageTrackList = resData.messageTrackList
        console.log('messageView', messageView)
        try {
          record.messageBody = JSON.parse(messageView.messageBody)
        } catch (e) {
          record.isJson = false
          record.messageBody = {'>': JSON.stringify(messageView.messageBody)}
        }
        setMsgDataList(record.messageTrackList)
        setMsgDetail(record.messageBody)
      }
    }
  }

  async function viewMessageTraceDetail() {
    // @ts-ignore
    let url =
      '/messageTrace/viewMessageTraceDetail.query?msgId=' +
      prop.record.msgId +
      '&topic=' +
      prop.record.topic
    const res = await HttpRequest({
      baseURL: defaultDomain,
      url: url,
      method: 'GET',
      params: {},
    })

    console.log('res=', res)
    // @ts-ignore
    const status = res.status
    if (status === 0) {
      const resData = res.data
      if (resData) {
        setTrackDataList(resData)
      }
    }
  }

  async function sendMessage(groupId: string) {
    let url =
      '/message/consumeMessageDirectly.do?consumerGroup=' +
      groupId +
      '&msgId=' +
      prop.record.msgId +
      '&topic=' +
      prop.record.topic
    const res = await HttpRequest({
      baseURL: defaultDomain,
      url: url,
      method: 'POST',
      params: {},
    })

    console.log('res=', res)
    // @ts-ignore
    const status = res.status
    if (status === 0) {
      message.success('消息重发成功！')
    } else {
      message.error('消息重发失败！>>' + res.errMsg)
    }
  }

  return (
    <ModalForm
      key="msgDetail"
      title={`消息ID [${prop.record.msgId}] 详情`}
      onVisibleChange={async (v) => {
        prop.record.mv = v
        if (v) {
          await getMessage(prop.record)
          await viewMessageTraceDetail()
        }
      }}
      trigger={<Button type="link">消息详情</Button>}
      width="80%"
      onFinish={async () => true}
    >
      <div className="site-card-wrapper">
        <Tabs defaultActiveKey="1">
          <TabPane tab="消息详情" key="1">
            <Row gutter={24}>
              <Col span={20}>
                <Descriptions title="基本信息" bordered>
                  <Descriptions.Item label="topic">
                    {prop.record.topic}
                  </Descriptions.Item>
                  <Descriptions.Item label="tag">
                    &nbsp;{prop.record.tag}
                  </Descriptions.Item>
                  <Descriptions.Item label="key">
                    &nbsp;{prop.record.key}
                  </Descriptions.Item>
                  <Descriptions.Item label="发送主机">
                    {prop.record.storeHost}
                  </Descriptions.Item>
                  <Descriptions.Item label="生成时间">
                    {FormatDateTime(prop.record.bornTimestamp / 1000)}
                  </Descriptions.Item>
                </Descriptions>
              </Col>
            </Row>

            <Row gutter={24}>
              <Col span={22} style={{marginTop: '10px'}}>
                <Descriptions title="消息详情" bordered>
                  <Descriptions.Item>
                    <ReactJson
                      iconStyle="triangle"
                      collapsed={1}
                      theme="paraiso"
                      displayDataTypes={false}
                      displayObjectSize={false}
                      src={msgDetail}
                    />
                  </Descriptions.Item>
                </Descriptions>
              </Col>
            </Row>
          </TabPane>
          <TabPane tab="消息轨迹" key="2">
            <Row gutter={24}>
              <Col span={24} style={{marginTop: '10px', overflowY: 'auto'}}>
                <Table
                  dataSource={msgDataList}
                  style={{height: '360px'}}
                  pagination={{pageSize: 10}}
                  columns={[
                    {
                      title: '消费组',
                      align: 'center',
                      width: '30%',
                      dataIndex: 'consumerGroup',
                      key: 'consumerGroup',
                      render: (text, record) => (
                        <div
                          style={{
                            wordWrap: 'break-word',
                            wordBreak: 'break-word',
                          }}
                          onDoubleClick={() => {
                          }}
                        >
                          {text}
                        </div>
                      ),
                    },
                    {
                      title: '轨迹类型',
                      align: 'center',
                      width: '10%',
                      dataIndex: 'trackType',
                      key: 'trackType',
                    },
                    {
                      title: '错误描述',
                      align: 'center',
                      width: '20%',
                      dataIndex: 'exceptionDesc',
                      key: 'exceptionDesc',
                    },
                    {
                      title: '操作',
                      align: 'center',
                      width: '20%',
                      dataIndex: 'action',
                      key: 'action',
                      render: (text, record) => {
                        return (
                          <div style={{cursor: 'pointer'}}>
                            <Tag
                              color="green"
                              onClick={() => {
                                // @ts-ignore
                                sendMessage(record.consumerGroup)
                              }}
                            >
                              消息重发
                            </Tag>
                          </div>
                        )
                      },
                    },
                  ]}
                />
              </Col>
            </Row>
          </TabPane>
          <TabPane tab="消息跟踪详细" key="3">
            <Row gutter={24}>
              <Col span={24} style={{marginTop: '10px', overflowY: 'auto'}}>
                <Table
                  dataSource={trackDataList}
                  style={{height: '360px'}}
                  pagination={{pageSize: 10}}
                  columns={[
                    {
                      title: '消息ID',
                      align: 'center',
                      width: '10%',
                      dataIndex: 'msgId',
                      key: 'msgId',
                      render: (text, record) => (
                        <div
                          onDoubleClick={() => {
                            onCopy(text, '消息ID')
                          }}
                          style={{
                            wordWrap: 'break-word',
                            wordBreak: 'break-word',
                          }}
                        >
                          {text}
                        </div>
                      ),
                    },
                    {
                      title: '主题',
                      align: 'center',
                      width: '10%',
                      dataIndex: 'topic',
                      key: 'topic',
                      render: (text, record) => (
                        <div
                          onDoubleClick={() => {
                            onCopy(text, 'topic')
                          }}
                          style={{
                            wordWrap: 'break-word',
                            wordBreak: 'break-word',
                          }}
                        >
                          {text}
                        </div>
                      ),
                    },
                    {
                      title: 'tags',
                      align: 'center',
                      width: '10%',
                      dataIndex: 'tags',
                      key: 'tags',
                    },

                    {
                      title: '分组名称',
                      align: 'center',
                      width: '10%',
                      dataIndex: 'groupName',
                      key: 'groupName',
                      render: (text, record) => (
                        <div
                          onDoubleClick={() => {
                            onCopy(text, 'groupName')
                          }}
                          style={{
                            wordWrap: 'break-word',
                            wordBreak: 'break-word',
                          }}
                        >
                          {text}
                        </div>
                      ),
                    },

                    {
                      title: '消息类型',
                      align: 'center',
                      width: '10%',
                      dataIndex: 'msgType',
                      key: 'msgType',
                    },
                    {
                      title: '消息ID偏移量',
                      align: 'center',
                      width: '10%',
                      dataIndex: 'offSetMsgId',
                      key: 'offSetMsgId',
                      render: (text, record) => (
                        <div
                          onDoubleClick={() => {
                            onCopy(text, 'offSetMsgId')
                          }}
                          style={{
                            wordWrap: 'break-word',
                            wordBreak: 'break-word',
                          }}
                        >
                          {text}
                        </div>
                      ),
                    },
                    {
                      title: '发送主机',
                      align: 'center',
                      width: '10%',
                      dataIndex: 'storeHost',
                      key: 'storeHost',
                    },
                    {
                      title: '创建时间',
                      align: 'center',
                      width: '10%',
                      dataIndex: 'timeStamp',
                      key: 'timeStamp',
                      render: (text, record:any) => (
                        <div
                          style={{
                            wordWrap: 'break-word',
                            wordBreak: 'break-word',
                          }}
                          onDoubleClick={() => {
                          }}
                        >
                          // @ts-ignore
                          {FormatDateTime(record.timeStamp / 1000)}
                        </div>
                      ),
                    },

                    {
                      title: '消耗时间',
                      align: 'center',
                      width: '10%',
                      dataIndex: 'costTime',
                      key: 'costTime',
                    },
                  ]}
                />
              </Col>
            </Row>
          </TabPane>
        </Tabs>
      </div>
    </ModalForm>
  )
}
